package com.sakura.random_team;

import java.util.Random;

public class DivideSystem {
    private final String[] playerList;
    public String[][] teams = null;
    public DivideSystem(int teamCount, String... playerList){
        this.playerList = playerList;
        this.teams = new String[teamCount][playerList.length / teamCount + 5];
    }
    private void divide(){
            int teamCount = this.teams.length;
            int average = this.playerList.length / teamCount;
            int left = this.playerList.length % teamCount;
            Random random = new Random();
            String[] playerList = this.playerList.clone();
            for (int i = 0; i < teamCount; i++) {
                for (int j = 0; j < average; j++) {
                    int i1 = random.nextInt(playerList.length);
                    this.teams[i][j] = playerList[i1];
                    playerList = deleteSingle(playerList, i1);
                }
            }
            int[] tempTeams = new int[teamCount];
            while (left != 0){
                int i = random.nextInt(playerList.length);
                int i1 = random.nextInt(tempTeams.length);
                if (tempTeams[i1] != -4){
                    this.teams[i1][average] = playerList[i];
                    tempTeams[i1] = -4;
                    left--;
                }
            }
    }
    public String[][] getResult(){
        divide();
        return this.teams;
    }
    public static String[] deleteSingle(String[] array, int index){
        String[] newArray = new String[array.length - 1];
        int k = 0;
        String s = array[index];
        for (String string : array) {
            if (s == string) {
                continue;
            }
            newArray[k] = string;
            k++;
        }
        return newArray;
    }
}